﻿/*------------------------------------------------------------
 * <copyright file="UnitQueryControl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang Jun</author>
 * <summary>
 *     *** UNIT别 期间别 查询 ***
 *      引用服务：WCFServers.UnitQueryRef
 *      服务功能：数据查询
 *   
 *      引用服务：WCFLog4Ref.WCFLog4Client
 *      服务功能：记录日志
 *
 *      (界面)StackPanel的控件名和TextBox控件名相同
 *       Button与StackPanel的名称相同
 *       
 *      作成日：06/28/2010
 *              08/11/2010 -- 增加导出功能
 *              09/28/0210 增加 分页记录数可自定义
 *              10/14/2010 修改 导出功能异常
 *              10/18/2010 修改 点击标题头排序时，导出内容不是排序结果的问题。
 *              05/16/2011 -- 增加 部分数据合计统计
 * </summary>
 *------------------------------------------------------------
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.ProductionRelated.UnitDurationQuery
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.Export;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.UnitQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Command = Orid.Management.Statistics.OperatorUnitMangement.Command;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;
    using System.ComponentModel;

    /// <summary>
    /// unit别 期间别 查询
    /// UserControl
    /// </summary>
    public partial class UnitQueryControl : UserControl
    {
        #region 全局变量
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " UNIT别期间别 ";

        /// <summary>
        /// 查询区域对象
        /// UnitSelAllContainter
        /// </summary>
        private UnitSelAllContainter unitSelallcontainer;

        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient;

        /// <summary>
        /// 消息子窗体
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// 存放导出数据
        /// </summary>
        private DataGrid dataToCSV = null;

        /// <summary>
        /// 记录总数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private int sumRecordCount = 0;

        /// <summary>
        /// 记录NumericUpDown分页数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private double oldNumericUpDown = 0;

        #region 部分数据合计统计 05/16/2011 Add

        /// <summary>
        /// 合计统计用存储数据
        /// </summary>
        /// <value>05/11/2011 Add</value>
        ObservableCollection<UnitDurationEntrySpeedQueryInforData> countDataItems;

        /// <summary>
        /// 合计统计结果
        /// </summary>
        /// <value>05/11/2011 Add</value>
        ///  字段名，合计结果
        Dictionary<string, decimal> countResultValues;


        /// <summary>
        /// 合计统计结果对应名称
        /// </summary>
        /// <value>05/11/2011 Add</value>
        /// 字段名，对应中文名
        Dictionary<string, string> countResultNames;

        #endregion 部分数据合计统计 05/16/2011 Add

        #endregion 全局变量

        /// <summary>
        /// 构造函数
        /// UnitQueryControl
        /// </summary>
        public UnitQueryControl(UnitSelAllContainter unitSelallcontainer)
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);
            this.dgUnitEntrySpeedQuery.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.unitSelallcontainer = unitSelallcontainer;

            this.wcfLogClient = Wcf.Service.Log4;

            this.errorMessbox = new childWindow.MessageBox();

            this.dataToCSV = new DataGrid();

            #region 查询按钮设置
            Command.UNIT.UnitDurEctrySpeedQuery queryCommand = new Command.UNIT.UnitDurEctrySpeedQuery(unitSelallcontainer);

            queryCommand.ExecOver -= new EventHandler<SelectUnitDurationEntrySpeedQueryInforCompletedEventArgs>(queryCommand_ExecOver);
            queryCommand.ExecBegin -= new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            queryCommand.ExecOver += new EventHandler<SelectUnitDurationEntrySpeedQueryInforCompletedEventArgs>(queryCommand_ExecOver);
            queryCommand.ExecBegin += new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            this.unitSelallcontainer.QueryCcommand = queryCommand;
            #endregion 查询按钮设置

            #region 导出设置
            //导出
            Command.DateExport exportCommand = new Command.DateExport();
            //导出开始
            exportCommand.ExecBegin += new EventHandler<EventArgs>(this.ExportCommand_ExecBegin);

            this.unitSelallcontainer.ExportComand = exportCommand;

            #endregion 导出设置


            //设置 查询界面 的 查询按钮 初始化可用
            this.unitSelallcontainer.btnSelectAllInfor.IsEnabled = true;
            this.unitSelallcontainer.btnExport.IsEnabled = true;
            this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));

        }

        #region BusyBar
        /// <summary>
        /// 让BusyBar开始
        /// SetBusyBar
        /// </summary>
        /// <param name="busySeconds">busy秒数 busysecond</param>
        public void SetBusyBar(int busySeconds)
        {
            int delayMilliseconds = 2;
            biBusyBar.DisplayAfter = TimeSpan.FromMilliseconds(delayMilliseconds);

            DataContext = true;
            this.nuPageSize.IsEnabled = false; //分页数量 09/28/2010 Add
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busySeconds * 1000);
            });
        }
        #endregion BusyBar

        #region 查询符合条件的OP信息

        /// <summary>
        /// 查询符合条件的OP信息(查询按钮)
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of SelectOPEntrySpeedQueryInforCompletedEventArgs</param>
        private void queryCommand_ExecOver(object sender, SelectUnitDurationEntrySpeedQueryInforCompletedEventArgs e)
        {
            try
            {
                //设置 查询界面 的 查询按钮 初始化可用
                this.unitSelallcontainer.btnSelectAllInfor.IsEnabled = true;

                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {

                        //记录所查询的记录总数（导出结果与排序内容一致用）
                        this.sumRecordCount = e.Result.Count;

                        this.pcv = new PagedCollectionView(e.Result);
                        this.pcv.PageSize = Convert.ToInt32(this.nuPageSize.Value);

                        this.dgUnitEntrySpeedQuery.ItemsSource = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;

                        this.dataToCSV.ItemsSource = null;
                        this.dataToCSV.ItemsSource = e.Result;

                        Dispatcher.BeginInvoke(() => DataContext = false);
                        this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                        #region BackgroundWorker线程 数据合计统计 05/16/2011 ADD

                        countDataItems = e.Result;

                        countResultValues = new Dictionary<string, decimal>();
                        countResultNames = new Dictionary<string, string>();
                        // 子画像件数ChildDataCount  正确子画像件数OKChildDataCount  文字数WordCount  录入时长Duration
                        countResultNames.Add("ChildDataCount", "  子画像件数:");
                        countResultNames.Add("OKChildDataCount", "  正确子画像件数:");
                        countResultNames.Add("WordCount", "  文字数:");
                        countResultNames.Add("Duration", "  录入时长:");

                        BackgroundWorker countThread = new BackgroundWorker();
                        countThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(countThread_RunWorkerCompleted);
                        countThread.DoWork += new DoWorkEventHandler(countThread_DoWork);
                        countThread.RunWorkerAsync();

                        #endregion 数据合计统计

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                    "在" +this.ctrlName + "查询中查询记录" +
                                                    unitSelallcontainer.WhereIntorLogs );
                    }
                    else
                    {
                        this.dgUnitEntrySpeedQuery.ItemsSource = null;
                        this.dpDataPage.DataContext = null;
                        this.dataToCSV.ItemsSource = null;
                        this.tbCountText.Text = string.Empty; // 统计清空

                        throw new Exception(this.ctrlName + " 查询中没有可显示的Unit数据");
                    }

                }
                else
                {
                    throw (new Exception("SelectUnitEntrySpeedQueryInfor服务返回值有错" + e.Error.Message.ToString()));
                }
            }
            catch (Exception exce)
            {
                string exceptionStr = FunctionClass.GetMessageInformation(exce);

                Dispatcher.BeginInvoke(() => DataContext = false);
                this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                                ctrlName +
                                                                exceptionStr +
                                                                unitSelallcontainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   exceptionStr,
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 查询符合条件的OP信息(查询按钮)

        /// <summary>
        /// 查询开始
        /// QueryCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void QueryCommand_ExecBegin(object sender, EventArgs e)
        {
            this.SetBusyBar(100);
        }

        #region 数据导出  08/11/2010 -- ADD
        /// <summary>
        /// 导出开始
        /// ExportCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void ExportCommand_ExecBegin(object sender, EventArgs e)
        {
            this.ExportDate();
        }

        /// <summary>
        /// 导出 按钮  
        /// ExportDate
        /// </summary>        
        private void ExportDate()
        {
            try
            {
                //设置 查询界面 的 数据导出 可用
                this.unitSelallcontainer.btnExport.IsEnabled = true;

                if (this.dgUnitEntrySpeedQuery.ItemsSource == null)
                {
                    throw new Exception("请查询后再将数据导出。");
                }
                else
                {
                    //导出结果与排序内容一致用
                    this.oldNumericUpDown = this.nuPageSize.Value;
                    this.pcv.PageSize = this.sumRecordCount;
                    this.dataToCSV.ItemsSource = this.pcv;

                    this.ExportDataToFile(this.dgUnitEntrySpeedQuery);
                }
            }
            catch (Exception ex)
            {

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                " ExportDate(" + this.ctrlName + ") " + 
                                                ex.Message.ToString() +
                                                unitSelallcontainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 数据导出
        /// ExportDataToFile
        /// </summary>
        /// <param name="grid">带有显示格式的 grid</param>
        /// <value>10/14/2010 修改 导出功能异常</value>
        private void ExportDataToFile(DataGrid grid)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";

                sfd.FilterIndex = 1;
                bool? ret = sfd.ShowDialog();
                if (ret == true)
                {
                    string data = DataExport.ExportDataGrid(true, grid, this.dataToCSV, null);

                    using (System.IO.Stream stream = sfd.OpenFile())
                    {
                        using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))
                        {
                            //由 逗号 换成 ^ ,--07/30/2010--EIDT 修改 千分位分割符用TAB替换问题
                            data = data.Replace("^", "\t");
                            writer.Write(data);
                            writer.Close();
                        }

                        stream.Close();
                    }
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                    "在 " + this.ctrlName + " 查询中导出记录" +
                                                    unitSelallcontainer.WhereIntorLogs);
                    FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      0,
                     "提示",
                     "数据已导出。",
                     Colors.Gray,
                     true,
                     Visibility.Visible,
                     Visibility.Collapsed);
                    return;
                }
                else
                {
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    return;
                }
            }
            catch (Exception ex)
            {
                this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                            " ExportDataToFile(" + this.ctrlName + ") " +
                                            ex.Message.ToString()+
                                            unitSelallcontainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 数据导出

        #region 部分数据合计统计 05/16/2011 Add
        /// <summary>
        ///  统计
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void countThread_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (var keyName in countResultNames)
            {
                var countresult = countDataItems.Sum(b => Convert.ToDecimal(b.GetType().GetProperty(keyName.Key).GetValue(b, null)));
                // 子画像件数ChildDataCount  正确子画像件数OKChildDataCount  文字数WordCount  录入时长Duration
                countResultValues.Add(keyName.Key, countresult);
            }
            e.Result = e.Argument;
        }

        /// <summary>
        /// 统计后输出
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        void countThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StringBuilder results = new StringBuilder();

            foreach (var keyName in countResultNames)
            {
                foreach (var keys in countResultValues)
                {

                    if (keys.Key == keyName.Key)
                    {
                        results.Append(countResultNames[keys.Key]);
                        results.Append(countResultValues[keys.Key].ToString("#,##0.##"));

                    }
                }

            }

            this.tbCountText.Text = results.ToString();
        }

        #endregion 部分数据合计统计
    }
}
